import Mock from 'mockjs'
import { getQueryParameters } from '../util'

const bookList = []
const bookCount = 50

for (let i = 0; i < bookCount; i++) {
  bookList.push(Mock.mock({
    id: '@id',
    title: '@ctitle(5, 20)',
    author: '@cname',
    cover: '@image("400x600")',
    description: '@cparagraph(1, 3)',
    'category|1': ['小说', '文学', '历史', '科技', '教育'],
    price: '@float(10, 100, 2, 2)',
    sales: '@integer(100, 10000)',
    createTime: '@datetime',
    'status|1': ['online', 'offline']
  }))
}

export default {
  // 获取书籍列表
  'GET /api/books': (req) => {
    const params = getQueryParameters(req)
    const { page = 1, pageSize = 10, category } = params
    
    let list = category ? bookList.filter(book => book.category === category) : bookList
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    list = list.slice(start, end)

    return {
      code: 200,
      data: {
        list,
        pagination: {
          total: bookList.length,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      },
      message: '获取成功'
    }
  },

  // 获取书籍详情
  'GET /api/books/:id': (req) => {
    const { id } = req.params
    const book = bookList.find(item => item.id === id)
    
    return {
      code: 200,
      data: book || bookList[0],
      message: '获取成功'
    }
  },
}